import 'dart:ui';

import 'package:flutter/rendering.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../public.dart';

class BookSheet extends StatefulWidget {
  @override
  _BookSheet createState() => _BookSheet();
}

class _BookSheet extends State<BookSheet> with AutomaticKeepAliveClientMixin {
//  @override
//  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
//  HideAlways
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
//    super.build(context);
    return ProviderWidget<BookSheetModel>(
        model: BookSheetModel(Provider.of<ThemeModel>(context)),
        onModelReady: (model) async => model.initData(),
        builder: (context, model, child) {
          if (model.busy) {
            return ViewStateBusyWidget();
          } else if (model.error) {
            return ViewStateWidget(onPressed: model.initData);
          } else if (model.empty) {
            return ViewStateEmptyWidget(onPressed: model.initData);
          }
          return SafeArea(
            child: Container(
              color: model.themeModel.customThemeData.mainColor,
              child: SmartRefresher(
                enablePullDown: true,
                enablePullUp: false,
                controller: _refreshController,
                header: MaterialClassicHeader(
                  color: model.themeModel.customThemeData.mainTextColor,
                  backgroundColor:
                      model.themeModel.customThemeData.mainBackgroundColor,
                ),
                onRefresh: () async {
                  //我在下拉刷新时执行
                  await model.refresh();
                  // if failed,use refreshFailed()
                  _refreshController.refreshCompleted();
                },
                physics: BouncingScrollPhysics(),
                child: Container(
                  child: SingleChildScrollView(
                    child: Column(
                      children: <Widget>[
                        _buildSearchBar(model),
                        _buildBookList(model, name: "我的书架", list: model.list),
                        _buildBookList(model,
                            name: "猜你喜欢", list: model.recommendList, type: 2),
                        _buildBookList2(model,
                            name: "热门推荐", list: model.hotList)
                      ],
                    ),
                  ),
                ),
              ),
            ),
          );
        });
  }

  Widget _buildSearchBar(BookSheetModel model) {
    return GestureDetector(
      onTap: () {
        AppConfig.router.navigateTo(context, '/search_book',
            transition: TransitionType.native);
      },
      child: Container(
        width: ScreenUtil().setWidth(750 * 0.9),
        margin: EdgeInsets.all(ScreenUtil().setWidth(750 * 0.05)),
        padding: EdgeInsets.symmetric(horizontal: ScreenUtil().setWidth(40)),
        height: ScreenUtil().setHeight(60),
        decoration: BoxDecoration(
            color: model.themeModel.customThemeData.mainBackgroundColor,
            borderRadius:
                BorderRadius.all(Radius.circular(ScreenUtil().setWidth(100)))),
        child: Row(
          children: <Widget>[
            Icon(
              IconFonts.search,
              color: model.themeModel.customThemeData.mainTextColor
                  .withOpacity(0.7),
              size: ScreenUtil().setSp(36, allowFontScalingSelf: true),
            ),
            Container(
              width: ScreenUtil().setWidth(10),
            ),
            Text(
              "雪中悍刀行",
              style: TextStyle(
                  fontSize: ScreenUtil().setSp(26, allowFontScalingSelf: true),
                  color: model.themeModel.customThemeData.mainTextColor
                      .withOpacity(0.7)),
            )
          ],
        ),
      ),
    );
  }

  Widget _buildBookList(BookSheetModel model,
      {String name, List<Book> list, type: 1}) {
    if (list == null) list = [];

    return Container(
      width: ScreenUtil().setWidth(750 * 0.9),
      margin: EdgeInsets.fromLTRB(
        ScreenUtil().setWidth(750 * 0.05),
        0,
        ScreenUtil().setWidth(750 * 0.05),
        ScreenUtil().setWidth(750 * 0.05),
      ),
      child: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.centerLeft,
            child: Text(
              name,
              style: TextStyle(
                fontFamily: "xiaowei",
                fontSize: ScreenUtil().setSp(36, allowFontScalingSelf: true),
                color: model.themeModel.customThemeData.mainTextColor
                    .withOpacity(0.8),
              ),
            ),
          ),
          Container(
            height: ScreenUtil().setHeight(320),
            child: () {
              if (list.length == 0) {
                return Container(
                  child: Center(
                    child: ViewStateBusyWidget(),
                  ),
                );
              }
              return CustomScrollView(
                scrollDirection: Axis.horizontal,
                physics: BouncingScrollPhysics(),
                slivers: <Widget>[
                  SliverList(
                      delegate: SliverChildListDelegate(
                          _buildBookItems(model, list: list, type: type)))
                ],
              );
            }(),
          )
        ],
      ),
    );
  }

  Widget _buildBookList2(BookSheetModel model, {String name, List<Book> list}) {
    if (list == null) list = [];

    return Container(
      width: ScreenUtil().setWidth(750 * 0.9),
      margin: EdgeInsets.fromLTRB(
        ScreenUtil().setWidth(750 * 0.05),
        0,
        ScreenUtil().setWidth(750 * 0.05),
        ScreenUtil().setWidth(750 * 0.05),
      ),
      child: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.centerLeft,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  name,
                  style: TextStyle(
                    fontFamily: "xiaowei",
                    fontSize:
                        ScreenUtil().setSp(36, allowFontScalingSelf: true),
                    color: model.themeModel.customThemeData.mainTextColor
                        .withOpacity(0.8),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    AppConfig.router.navigateTo(context, "/retrieval",
                        transition: TransitionType.inFromRight);
                  },
                  child: Container(
                    child: Text.rich(TextSpan(children: [
                      TextSpan(
                        text: "更多",
                        style: TextStyle(
                          fontFamily: "xiaowei",
                          fontSize: ScreenUtil()
                              .setSp(28, allowFontScalingSelf: true),
                          color: model.themeModel.customThemeData.mainTextColor
                              .withOpacity(0.6),
                        ),
                      ),
                      TextSpan(
                          text: "\ue6a8",
                          style: TextStyle(
                            fontFamily: "iconfont_icon",
                            fontSize: ScreenUtil()
                                .setSp(28, allowFontScalingSelf: true),
                            color: model
                                .themeModel.customThemeData.mainTextColor
                                .withOpacity(0.6),
                          ))
                    ])),
                  ),
                )
              ],
            ),
          ),
          Container(
            alignment: Alignment.centerLeft,
            child: () {
              if (list.length == 0) {
                return Container(
                  height: ScreenUtil().setHeight(300),
                  child: Center(
                    child: ViewStateBusyWidget(),
                  ),
                );
              }
              return Column(
                children: _buildBookItems2(model, list: list),
              );
            }(),
          )
        ],
      ),
    );
  }

  List<Widget> _buildBookItems(BookSheetModel model,
      {List<Book> list, type: 1}) {
    List<Widget> _list = [];
    for (int index = 0; index < list.length; index++) {
      Book _item = list[index];
      _list.add(
        InkWell(
          onLongPress: () {
            if (type == 1) {
              showDialog(
                context: context,
                builder: (ctx) => Padding(
                  padding: EdgeInsets.all(ScreenUtil().setWidth(8)),
                  child: CustomDialog(
                    bgColor: model.themeModel.customThemeData.mainColor,
                    txtColor: model.themeModel.customThemeData.mainTextColor,
                    title: "确认删除？",
                    confirm: () {
                      model.deleteBook(_item.bookId);
                      Navigator.pop(context);
                    },
                  ),
                ),
              );
            }
          },
          onTap: () {
            String title = Uri.encodeComponent(_item.title) ?? "";
            String url = Uri.encodeComponent(_item.originUrl) ?? "";
            String author = Uri.encodeComponent(_item.author) ?? "";
            String reptileType = Uri.encodeComponent(_item.reptileType) ?? "";
            String reptileType1 = Uri.encodeComponent(_item.reptileType1) ?? "";
            String now = type == 1 ? Uri.encodeComponent(_item.now) ?? "" : "0";
            var route = "/book_info?"
                "title=$title&"
                "author=$author&"
                "url=$url&"
                "now=$now&"
                "reptileType=$reptileType&"
                "reptileType1=$reptileType1&";
            AppConfig.router.navigateTo(context, route,
                transition: TransitionType.inFromRight);
          },
          child: Container(
            width: ScreenUtil().setWidth(200),
            margin: EdgeInsets.fromLTRB(
              index == 0 ? 0 : ScreenUtil().setHeight(10),
              ScreenUtil().setHeight(20),
              index == 4
                  ? ScreenUtil().setHeight(20)
                  : ScreenUtil().setHeight(10),
              ScreenUtil().setHeight(5),
            ),
            child: Column(
              children: <Widget>[
                Container(
                  height: ScreenUtil().setHeight(230),
                  width: ScreenUtil().setWidth(200),
                  child: ClipRRect(
                    borderRadius:
                        BorderRadius.circular(ScreenUtil().setWidth(5)),
                    child: Stack(
                      fit: StackFit.expand,
                      children: <Widget>[
                        CachedImage(
                          url: _item.bookId != null
                              ? AppConfig.IMG_BASE_UEL.toString() +
                                  "images/" +
                                  _item.bookId.toString()
                              : _item.imgUrl,
                          fit: BoxFit.cover,
                        ),
                        Positioned(
                          left: 0,
                          top: 0,
                          height: ScreenUtil().setHeight(230),
                          width: ScreenUtil().setWidth(200),
                          child: Container(
                            color: Color.fromARGB(40, 0, 0, 0),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                Container(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    _item.title,
                    maxLines: 1,
                    textAlign: TextAlign.left,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: model.themeModel.customThemeData.mainTextColor
                          .withOpacity(0.6),
                      fontSize:
                          ScreenUtil().setSp(24, allowFontScalingSelf: true),
                    ),
                  ),
                ),
                type == 1
                    ? Container(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          "已阅读：${((int.parse(_item.now) / int.parse(_item.total)) * 100).toStringAsFixed(2)}%",
                          maxLines: 1,
                          textAlign: TextAlign.left,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: model
                                .themeModel.customThemeData.mainBackgroundColor,
                            fontSize: ScreenUtil()
                                .setSp(18, allowFontScalingSelf: true),
                          ),
                        ),
                      )
                    : Container(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          "${_item.bookType}",
                          maxLines: 1,
                          textAlign: TextAlign.left,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: model
                                .themeModel.customThemeData.mainBackgroundColor,
                            fontSize: ScreenUtil()
                                .setSp(18, allowFontScalingSelf: true),
                          ),
                        ),
                      )
              ],
            ),
          ),
        ),
      );
    }
    return _list;
  }

  List<Widget> _buildBookItems2(BookSheetModel model, {List<Book> list}) {
    List<Widget> _list = [];
    for (int index = 0; index < list.length; index++) {
      Book _item = list[index];
      _list.add(
        InkWell(
          onTap: () {
            String title = Uri.encodeComponent(_item.title) ?? "";
            String url = Uri.encodeComponent(_item.originUrl) ?? "";
            String author = Uri.encodeComponent(_item.author) ?? "";
            String reptileType = Uri.encodeComponent(_item.reptileType) ?? "";
            String reptileType1 = Uri.encodeComponent(_item.reptileType1) ?? "";
            var route = "/book_info?"
                "title=$title&"
                "author=$author&"
                "url=$url&"
                "now=0&"
                "reptileType=$reptileType&"
                "reptileType1=$reptileType1&";
            AppConfig.router.navigateTo(context, route,
                transition: TransitionType.inFromRight);
          },
          child: Container(
            width: ScreenUtil().setWidth(750 * 0.9),
            margin: EdgeInsets.fromLTRB(
              0,
              ScreenUtil().setHeight(20),
              0,
              ScreenUtil().setHeight(5),
            ),
            child: Row(
              children: <Widget>[
                Container(
                  height: ScreenUtil().setHeight(230),
                  width: ScreenUtil().setWidth(200),
                  child: ClipRRect(
                    borderRadius:
                        BorderRadius.circular(ScreenUtil().setWidth(5)),
                    child: Stack(
                      fit: StackFit.expand,
                      children: <Widget>[
                        CachedImage(
                          url: _item.imgUrl,
                          fit: BoxFit.cover,
                        ),
                        Positioned(
                          left: 0,
                          top: 0,
                          height: ScreenUtil().setHeight(230),
                          width: ScreenUtil().setWidth(200),
                          child: Container(
                            color: Color.fromARGB(40, 0, 0, 0),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                Container(
                  width: ScreenUtil().setWidth(750 * 0.9) -
                      ScreenUtil().setWidth(220),
                  decoration: BoxDecoration(),
                  margin:
                      EdgeInsets.fromLTRB(ScreenUtil().setWidth(20), 0, 0, 0),
                  child: Column(
                    children: <Widget>[
                      Container(
                        height: ScreenUtil().setHeight(30),
                        alignment: Alignment.topLeft,
                        child: Text(
                          _item.title,
                          softWrap: true,
                          maxLines: 1,
                          textAlign: TextAlign.left,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: model
                                .themeModel.customThemeData.mainTextColor
                                .withOpacity(0.6),
                            fontSize: ScreenUtil()
                                .setSp(28, allowFontScalingSelf: true),
                          ),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.fromLTRB(
                          0,
                          ScreenUtil().setHeight(5),
                          0,
                          ScreenUtil().setHeight(25),
                        ),
                        alignment: Alignment.topLeft,
                        child: Text(
                          _item.author,
                          softWrap: true,
                          maxLines: 1,
                          textAlign: TextAlign.left,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: model
                                .themeModel.customThemeData.mainBackgroundColor,
                            fontSize: ScreenUtil()
                                .setSp(24, allowFontScalingSelf: true),
                          ),
                        ),
                      ),
                      Container(
                        height: ScreenUtil().setHeight(150),
                        alignment: Alignment.topLeft,
                        child: Text(
                          _item.description ?? "暂无简介",
                          maxLines: 8,
                          textAlign: TextAlign.justify,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: model
                                .themeModel.customThemeData.mainBackgroundColor,
                            fontSize: ScreenUtil()
                                .setSp(18, allowFontScalingSelf: true),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }
    return _list;
  }
}
